package com.duoduo.双指针;

/**
 * @program: algorithm
 * @description: 轮转数组
 * 给你一个数组，将数组中的元素向右轮转 k 个位置，其中 k 是非负数。
 * 输入: nums = [1,2,3,4,5,6,7], k = 3
 * 输出: [5,6,7,1,2,3,4]
 * 解释:
 * 向右轮转 1 步: [7,1,2,3,4,5,6]
 * 向右轮转 2 步: [6,7,1,2,3,4,5]
 * 向右轮转 3 步: [5,6,7,1,2,3,4]
 * @author: chaidl  ！
 * @create: 2022-03-14 20:52
 */
public class 轮转数组 {
    public static void main(String[] args) {
        int[] test = {1, 2, 3, 4, 5, 6, 7};
        rotate(test, 3);
    }

    //使用额外的数组
    public static int[] rotate1(int[] nums, int k) {
        int n = nums.length;
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            int kk = (i + k) % n;
            arr[kk] = nums[i];
        }
        System.arraycopy(arr, 0, nums, 0, n);
        return nums;
    }

    //数组的反转
    public static void rotate(int[] nums, int k) {
        k %= nums.length;
        //先将整个数组反转
        reverse(nums, 0, nums.length - 1);
        //将0-k数组反转
        reverse(nums, 0, k - 1);
        //将k-nums.length - 1数组反转
        reverse(nums, k, nums.length - 1);
    }

    private static void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int tmp = nums[start];
            nums[start] = nums[end];
            nums[end] = tmp;
            start += 1;
            end -= 1;
        }

    }
}
